package com.pms.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pms.domain.Batch;
import com.pms.domain.DOPU;
import com.pms.domain.DORCL;
import com.pms.domain.DORU;
import com.pms.domain.FTPSettings;
import com.pms.domain.JobConfig;
import com.pms.domain.MOFCRD;
import com.pms.domain.MOPB;
import com.pms.domain.MOPCB;
import com.pms.domain.WORB;
import com.pms.exception.AppException;
import com.pms.service.BatchService;
import com.pms.service.DOPUService;
import com.pms.service.DORCLService;
import com.pms.service.DORUService;
import com.pms.service.FTPSettingsService;
import com.pms.service.MOFCRDService;
import com.pms.service.MOPBService;
import com.pms.service.MOPCBService;
import com.pms.service.ReportService;
import com.pms.service.WORBService;
import com.pms.utils.FtpTools;

@Service("reportService")
public class ReportServiceImpl implements ReportService {

	public static Logger logger = Logger.getLogger(ReportServiceImpl.class);

	public static final String DELIMITER_1 = "%%@%%";
	public static final String DELIMITER_2 = "&";
	public static final String DELIMITER_3 = "\\|";
	public static final String DELIMITER_4 = "_";
	public static final String DELIMITER_5 = "%";

	@Autowired
	BatchService batchService;

	@Autowired
	MOPBService mOPBService;

	@Autowired
	MOPCBService mOPCBService;

	@Autowired
	DOPUService dOPUService;

	@Autowired
	DORCLService dORCLService;

	@Autowired
	DORUService dORUService;

	@Autowired
	WORBService wORBService;

	@Autowired
	MOFCRDService mOFCRDService;

	@Autowired
	FTPSettingsService fTPSettingsService;

	@Override
	public void handler(JobConfig cfg) {
		Date current = new Date();
		logger.info("*********" + current.toString() + "::jobcfg_id=" + cfg.getJobcfgid() + "定时任务开始执行*********");
		FTPSettings settings = fTPSettingsService.selectFTPSettingsById(cfg.getJobcfgid());
		if (settings != null) {

			List<String> list = listAllFile(settings);
			for (String fileName : list) {
				String checkFile = fileName + settings.getCheckfilesuffix();
				try {
					FtpTools.downFile(settings.getFtpserver(), settings.getFtpport(), settings.getFtpuser(),
							settings.getFtppassword(), settings.getRemotepath(), checkFile, fileName,
							settings.getLocalftppath());
					handleFile(fileName, settings.getTexfileencodeing(), settings.getLocalftppath(), cfg.getProjectid());

				} catch (NumberFormatException | AppException e) {
					logger.info(e.getMessage());
				}

			}
		}

		current = new Date();
		logger.info("*********" + current.toString() + "::jobcfg_id=" + cfg.getJobcfgid() + "定时任务执行结束*********");

	}

	private List<String> listAllFile(FTPSettings settings) {
		List<String> list = null;
		try {
			list = FtpTools.listAllTxtFile(settings.getFtpserver(), settings.getFtpport(), settings.getFtpuser(),
					settings.getFtppassword(), settings.getRemotepath(), settings.getCheckfilesuffix());
		} catch (NumberFormatException | AppException e) {
			e.printStackTrace();
		}

		return list;
	}

	private void handleFile(String fileName, String textFileEncodeing, String localFTPPath, Integer projectId) {

		int index = fileName.indexOf(".");
		String fileNameShort = fileName.substring(0, index);
		String fileSuffix = fileName.substring(index);
		Batch batch = new Batch();
		String delimiter;
		Integer batchCode;

		// D_OR_U,D_OR_CL,D_OP_U:
		// field[0],field[1],field[2]
		// field[3]:上传日期，field[4]:运营日期，field[5]:批次号，field[6]:分割符,field[7]:文件数量,field[8]:当前文件序号,field[9]:记录总数量,field[10]:当前文件记录数
		// W_OR_B,M_OP_CB,M_OP_B
		// M_OF_C_RD
		if (fileNameShort.startsWith("D_OR_U") || fileNameShort.startsWith("D_OR_CL")
				|| fileNameShort.startsWith("D_OP_U")) {
			String[] fields = fileNameShort.split("_");
			if (fields.length == 11) {
				batch.setBatchpre(fields[0] + fields[1] + fields[2]);
				batch.setBatchdate(fields[3]);
				batch.setBatchno(fields[5]);
				batch.setBatchsp(fields[6]);
				batch.setBatchnums(Integer.parseInt(fields[7]));
				batch.setBatchindex(fields[8]);
				batch.setBatchtotal(Integer.parseInt(fields[9]));
				batch.setBatchcount(Integer.parseInt(fields[10]));
				batch.setBilldate(fields[4]);
				batch.setFilename(fileName);
				batch.setProjectid(projectId);
				delimiter = getDelimiter(batch.getBatchsp());
				int state = 1;
				batch.setState(state);
				batchService.insertBatch(batch);
				batchCode = batch.getBatchcode();

				if (fileNameShort.startsWith("D_OP_U")) {
					state = handleFileContentDOPU(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				} else if (fileNameShort.startsWith("D_OR_CL")) {
					state = handleFileContentDORCL(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				} else if (fileNameShort.startsWith("D_OR_U")) {
					state = handleFileContentDORU(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				}

				batch.setState(state);
				batchService.updateBatch(batch);
			}

		} else if (fileNameShort.startsWith("W_OR_B") || fileNameShort.startsWith("M_OP_CB")
				|| fileNameShort.startsWith("M_OP_B")) {
			String[] fields = fileNameShort.split("_");
			if (fields.length == 12) {
				batch.setBatchpre(fields[0] + fields[1] + fields[2]);
				batch.setBatchdate(fields[3]);
				batch.setBatchno(fields[6]);
				batch.setBatchsp(fields[7]);
				batch.setBatchnums(Integer.parseInt(fields[8]));
				batch.setBatchindex(fields[9]);
				batch.setBatchtotal(Integer.parseInt(fields[10]));
				batch.setBatchcount(Integer.parseInt(fields[11]));
				batch.setBillstartdate(fields[4]);
				batch.setBillenddate(fields[5]);
				batch.setFilename(fileName);
				batch.setProjectid(projectId);
				delimiter = getDelimiter(batch.getBatchsp());
				int state = 1;
				batch.setState(state);
				batchService.insertBatch(batch);
				batchCode = batch.getBatchcode();

				if (fileNameShort.startsWith("W_OR_B")) {
					state = handleFileContentWORB(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				} else if (fileNameShort.startsWith("M_OP_CB")) {
					state = handleFileContentMOPCB(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				} else if (fileNameShort.startsWith("M_OP_B")) {
					state = handleFileContentMOPB(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
							localFTPPath);
				}

				batch.setState(state);
				batchService.updateBatch(batch);
			}

		} else if (fileNameShort.startsWith("M_OF_C_RD")) {
			String[] fields = fileNameShort.split("_");

			if (fields.length == 13) {
				batch.setBatchpre(fields[0] + fields[1] + fields[2] + fields[3]);
				batch.setBatchdate(fields[4]);
				batch.setBatchno(fields[7]);
				batch.setBatchsp(fields[8]);
				batch.setBatchnums(Integer.parseInt(fields[9]));
				batch.setBatchindex(fields[10]);
				batch.setBatchtotal(Integer.parseInt(fields[11]));
				batch.setBatchcount(Integer.parseInt(fields[12]));
				batch.setBillstartdate(fields[5]);
				batch.setBillenddate(fields[6]);
				batch.setFilename(fileName);
				batch.setProjectid(projectId);
				delimiter = getDelimiter(batch.getBatchsp());
				int state = 1;
				batch.setState(state);
				batchService.insertBatch(batch);
				batchCode = batch.getBatchcode();

				state = handleFileContentMOFCRD(fileName, fileSuffix, delimiter, batchCode, textFileEncodeing,
						localFTPPath);

				batch.setState(state);
				batchService.updateBatch(batch);
			}

		} else {
			logger.error(fileName + "文件名格式错误！");
		}
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentDOPU(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<DOPU> items = new ArrayList<DOPU>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {

				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {

					String[] fields = lineTxt.split(delimiter);

					if (fields.length == 12) {
						DOPU item = new DOPU();
						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setAddress(fields[4]);
						item.setEffectivetime(stringToDate(fields[5]));
						item.setPackagetype(fields[6]);
						item.setProductcode(fields[7]);
						item.setPackageamount(fields[8]);
						item.setContractperiod(fields[9]);
						item.setRealstate(stringToDate(fields[10]));
						item.setState(fields[11]);
						item.setBatchcode(batchCode);

						items.add(item);
					}
				}

				count++;
			}

			// 批量插入
			dOPUService.insertDOPU(items);
			result = 2;
			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}

		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentDORCL(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<DORCL> items = new ArrayList<DORCL>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {

					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 22) {
						DORCL item = new DORCL();

						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setProductcode(fields[4]);
						item.setPackagetype(fields[5]);
						item.setPackageamount(fields[6]);
						item.setFirstmonthfeetype(fields[7]);
						item.setMobilebrand(fields[8]);
						item.setSn(fields[9]);
						item.setImei(fields[10]);
						item.setAmount(new Double(fields[11]));
						item.setDownpaymentamount(new Double(fields[12]));
						item.setApplytime(stringToDate(fields[13]));
						item.setEffectivetime(stringToDate(fields[14]));
						item.setChanneltype(fields[15]);
						item.setChannelname(fields[16]);
						item.setChannelcode(fields[17]);
						item.setChanneladdress(fields[18]);
						item.setEmployeeno(fields[19]);
						item.setEmployeename(fields[20]);
						item.setOrdertype(fields[21]);
						// item.setContractperiod(fields[22]);

						items.add(item);
					}
				}

				count++;
			}

			// 批量插入
			dORCLService.insertDORCL(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentDORU(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<DORU> items = new ArrayList<DORU>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 22) {
						DORU item = new DORU();

						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setProductcode(fields[4]);
						item.setPackagetype(fields[5]);
						item.setPackageamount(fields[6]);
						item.setFirstmonthfeetype(fields[7]);
						item.setMobilebrand(fields[8]);
						item.setSn(fields[9]);
						item.setImei(fields[10]);
						item.setAmount(new Double(fields[11]));
						item.setDownpaymentamount(new Double(fields[12]));
						item.setApplytime(stringToDate(fields[13]));
						item.setEffectivetime(stringToDate(fields[14]));
						item.setChanneltype(fields[15]);
						item.setChannelname(fields[16]);
						item.setChannelcode(fields[17]);
						item.setChanneladdress(fields[18]);
						item.setEmployeeno(fields[19]);
						item.setEmployeename(fields[20]);
						item.setOrdertype(fields[21]);
						// item.setContractperiod(fields[22]);

						items.add(item);
					}

				}

				count++;
			}

			// 批量插入
			dORUService.insertDORUBatch(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentWORB(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<WORB> items = new ArrayList<WORB>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 23) {
						WORB item = new WORB();

						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setProductcode(fields[4]);
						item.setPackagetype(fields[5]);
						item.setPackageamount(fields[6]);
						item.setFirstmonthfeetype(fields[7]);
						item.setMobilebrand(fields[8]);
						item.setSn(fields[9]);
						item.setImei(fields[10]);
						item.setAmount(new Double(fields[11]));
						item.setDownpaymentamount(new Double(fields[12]));
						item.setApplytime(stringToDate(fields[13]));
						item.setEffectivetime(stringToDate(fields[14]));
						item.setChanneltype(fields[15]);
						item.setChannelname(fields[16]);
						item.setChannelcode(fields[17]);
						item.setChanneladdress(fields[18]);
						item.setEmployeeno(fields[19]);
						item.setEmployeename(fields[20]);
						item.setOrdertype(fields[21]);
						item.setContractperiod(fields[22]);

						items.add(item);
					}
				}
				count++;

			}

			// 批量插入
			wORBService.insertWORB(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentMOPCB(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<MOPCB> items = new ArrayList<MOPCB>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 12) {
						MOPCB item = new MOPCB();
						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setAddress(fields[4]);
						item.setEffectivetime(stringToDate(fields[5]));
						item.setPackagetype(fields[6]);
						item.setProductcode(fields[7]);
						item.setPackageamount(fields[8]);
						item.setContractperiod(fields[9]);
						item.setRealstate(stringToDate(fields[10]));
						item.setState(fields[11]);
						item.setBatchcode(batchCode);

						items.add(item);
					}
				}
				count++;
			}

			// 批量插入
			mOPCBService.insertMOPCBBatch(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentMOPB(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<MOPB> items = new ArrayList<MOPB>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 19) {
						MOPB item = new MOPB();
						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setAddress(fields[4]);
						item.setEffectivetime(stringToDate(fields[5]));
						item.setPackagetype(fields[6]);
						item.setProductcode(fields[7]);
						item.setPackageamount(fields[8]);
						item.setContractperiod(fields[9]);
						item.setEffectivemonth(fields[10]);
						item.setSettle(fields[11]);
						item.setAccumulatedpastdue(new Double(fields[12]));
						item.setCurrentmonthpastdue(new Double(fields[13]));
						item.setPaidcurrentmonthfee(new Double(fields[14]));
						item.setPastduepaid(new Double(fields[15]));
						item.setPastduepaidmonths(fields[16]);
						item.setPackageamountshare(new Double(fields[17]));
						item.setIncentive(new Double(fields[18]));
						item.setBatchcode(batchCode);
						items.add(item);
					}
				}
				count++;
			}

			// 批量插入
			mOPBService.insertMOPBBatch(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}

		return result;
	}

	/**
	 * 
	 * @param fileName
	 * @param fileSuffix
	 *            文件后缀，目前只处理.txt
	 * @param delimiter
	 * @param batchCode
	 * @return
	 */
	private int handleFileContentMOFCRD(String fileName, String fileSuffix, String delimiter, Integer batchCode,
			String textFileEncodeing, String localFTPPath) {
		int result = 0;
		List<MOFCRD> items = new ArrayList<MOFCRD>();
		String fileFullName = getFileFullName(fileName, localFTPPath);

		if (!(".txt".equals(fileSuffix))) {
			logger.error(fileName + "文件格式不支持！");
			result = 10;
			return result;
		}

		File file = new File(fileFullName);

		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), textFileEncodeing);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			int count = 0;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				if (count > 0 && (lineTxt != null) && lineTxt.length() > 10) {
					String[] fields = lineTxt.split(delimiter);
					if (fields.length == 28) {
						MOFCRD item = new MOFCRD();

						item.setName(fields[0]);
						item.setMobileno(fields[1]);
						item.setCerttype(fields[2]);
						item.setCertno(fields[3]);
						item.setPastduemonthno(fields[4]);
						item.setApplytime(stringToDate(fields[5]));
						item.setEffectivetime(stringToDate(fields[6]));
						item.setChanneltype(fields[7]);
						item.setChannelname(fields[8]);
						item.setChannelcode(fields[9]);
						item.setChanneladdress(fields[10]);
						item.setEmployeeno(fields[11]);
						item.setEmployeename(fields[12]);
						item.setProductcode(fields[13]);
						item.setPackagetype(fields[14]);
						item.setPackageamount(fields[15]);
						item.setFirstmonthfeetype(fields[16]);
						item.setMobilebrand(fields[17]);
						item.setSn(fields[18]);
						item.setImei(fields[19]);
						item.setContractamount(new Double(fields[20]));
						item.setDownpaymentamount(new Double(fields[21]));
						item.setMonth(new Integer(fields[22]));
						item.setTotalamount(new Double(fields[23]));
						item.setRecalltimes(new Integer(fields[24]));
						item.setRecallresult(fields[25]);
						item.setQa(fields[26]);
						item.setRecalltime(stringToDate(fields[27]));

						items.add(item);
					}
				}
				count++;
			}

			// 批量插入
			mOFCRDService.insertMOFCRDBatch(items);
			result = 2;

			read.close();
		} catch (UnsupportedEncodingException e) {
			result = 11;
			logger.error(fileName + e.getMessage());
		} catch (FileNotFoundException e) {
			result = 12;
			logger.error(fileName + e.getMessage());
		} catch (IOException e) {
			result = 13;
			logger.error(fileName + e.getMessage());
		}
		return result;
	}

	/**
	 * 从文件名中定义的字段分割符值转换为分隔符字符串
	 * 
	 * @param separator
	 * @return
	 */
	private String getDelimiter(String separator) {
		int sep = Integer.parseInt(separator);
		if (1 == sep)
			return DELIMITER_1;
		else if (2 == sep)
			return DELIMITER_2;
		else if (3 == sep)
			return DELIMITER_3;
		else if (4 == sep)
			return DELIMITER_4;
		else if (5 == sep)
			return DELIMITER_5;

		return DELIMITER_1;
	}

	/**
	 * 文件名加上绝对路径
	 * 
	 * @param fileName
	 * @return
	 */
	private String getFileFullName(String fileName, String localFTPPath) {
		StringBuffer buffer = new StringBuffer();
		if (localFTPPath.endsWith("/")) {
			buffer.append(localFTPPath);
			buffer.append(fileName);
		} else {
			buffer.append(localFTPPath);
			buffer.append("/");
			buffer.append(fileName);
		}

		return buffer.toString();

	}

	private Date stringToDate(String s) {
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		try {
			return format.parse(s);
		} catch (ParseException e) {
			// e.printStackTrace();
		}
		return null;
	}

}
